import { Button, Card, Form, Input, Select, Table, Tag, message } from 'antd'
import React, { useEffect, useState } from 'react'
import { SearchOutlined } from "@ant-design/icons"
import type { ColumnsType } from 'antd/lib/table';
import { ReqCityOrDistrictOrHostypeResponse, ReqHospitalList, ReqHospitalStatus, ReqProvinceListResponse } from '@/api/hospitalList/hospitalList';
import type { hospitalItemType, hospitalListType, provinceOrCityOrDistrictOrHostypeList } from '@/api/hospitalList/model/hospitalListTypes';
import { useForm } from 'antd/lib/form/Form';
import { useNavigate } from 'react-router-dom';

const { Option } = Select;

export default function HospiatlList() {

  //导入 navigate 函数
  let navigate = useNavigate();
  //获取 form
  let [form] = useForm();

  // 每页展示数量状态
  let [pageSize, setPageSize] = useState<number>(5);

  //当前页码状态
  let [current, setCurrent] = useState<number>(3);

  //总数
  let [total, setTotal] = useState<number>(20);

  //医院列表状态
  let [hospital, setHospital] = useState<hospitalListType>([]);

  //声明 loading 状态
  let [loading, setLoading] = useState<boolean>(false);

  //声明 省份状态
  let [province, setProvince] = useState<provinceOrCityOrDistrictOrHostypeList>([]);

  //声明 市状态
  let [city, setCity] = useState<provinceOrCityOrDistrictOrHostypeList>([]);

  //声明 区状态
  let [district, setDistrict] = useState<provinceOrCityOrDistrictOrHostypeList>([]);

  //声明 医院类型状态
  let [hostype, setHostype] = useState<provinceOrCityOrDistrictOrHostypeList>([]);


  //表格表头设置信息
  let columns: ColumnsType<any> = [
    {
      title: "序号",
      align: "center",
      width: 80,
      render(text, row, index) {
        return index + 1;
      }
    },
    {
      title: "医院logo",
      align: "center",
      dataIndex: "logoData",
      render(text) {
        return <img style={{ width: 100 }} src={`data:image/jpeg;base64,${text}`} alt="" />
      }
    },
    {
      title: "医院名称",
      align: "center",
      dataIndex: "hosname",
    },
    {
      title: "等级",
      width: 100,
      align: "center",
      dataIndex: "param",
      render(text) {
        return text.hostypeString;
      }
    },
    {
      title: "详细地址",
      align: "center",
      render(row: hospitalItemType) {
        return row.param.fullAddress
      }

    },
    {
      title: "状态",
      width: 100,
      align: "center",
      dataIndex: "status",
      render(text) {
        return text === 1 ? <Tag color="#108ee9">已上线</Tag> : <Tag color="#f50">未上线</Tag>;
      }
    },
    {
      title: "创建时间",
      align: "center",
      dataIndex: "createTime",
    },
    {
      title: "操作",
      width: 260,
      align: "center",
      fixed: "right",
      render(row:hospitalItemType) {
        return <>
          <Button type="primary" onClick={()=>{
              navigate(`/syt/hospital/hospitalList/show/${row.id}`);
          }}>查看</Button>
          <Button onClick={()=>{
            navigate(`/syt/hospital/hospitalList/schedule/${row.hoscode}`);
          }} type="primary" className='ml'>排班</Button>
          {
              row.status  === 1 ? 
              <Button onClick={updateStatus(row.id,row.status)} type="primary" danger className='ml'>下线</Button> : 
              <Button onClick={updateStatus(row.id,row.status)} type="primary" className='ml'>上线</Button>
          }
          

        </>
      }
    }
  ]


  //更新医院状态
  let updateStatus = (id:string,status:number)=>{
    return async ()=>{

      //修改医院状态
      status = status === 1 ? 0 : 1;
      //调用方法更新状态
      await ReqHospitalStatus({id,status});

      //提示
      message.success("更新医院状态成功！");
      
      // 重新请求数据
      getHospitalList();

    }
  }

  //获取医院列表数据
  let getHospitalList = async (page = current, limit = pageSize) => {
    //获取表单数据
    let values = form.getFieldsValue();
    // console.log(values);

     //清空 医院列表数据
     setHospital([]);

    //更新 每页展示数量状态
    setPageSize(limit);
    //更新页码状态
    setCurrent(page);
    //开启 loading
    setLoading(true);

    //调用 获取医院信息的方法
    let result = await ReqHospitalList({ page, limit, ...values });
    // console.log(result);

    //关闭 loading
    setLoading(false);

    //设置数据
    setHospital(result.content);
    //设置总数
    setTotal(result.totalElements)
  }

  //获取省份数据
  let getProvinceList = async () => {
    let result = await ReqProvinceListResponse();
    //  console.log(result);
    //更新省份数据
    setProvince(result);
  }

  //获取市数据
  let getCity = async (value: number) => {

    //清空 市 和区 表单数据
    form.setFieldsValue({ cityCode: undefined, districtCode: undefined });

    //清空 市 和区 状态
    setDistrict([]);

    //调用方法获取市数据
    let result = await ReqCityOrDistrictOrHostypeResponse(value);
    // console.log(result);
    //更新市状态
    setCity(result);
  }

  //获取区数据
  let getDistrict = async (value: number) => {
    //清空区 表单数据
    form.setFieldsValue({ districtCode: undefined });
    //调用方法获取区数据
    let result = await ReqCityOrDistrictOrHostypeResponse(value);
    // console.log(result);
    //更新区状态
    setDistrict(result);
  }

  //获取医院类型
  let getHospitalType = async () => {
    //调用方法获取医院类型数据
    let result = await ReqCityOrDistrictOrHostypeResponse(10000);
    // console.log(result);
    //更新医院类型状态
    setHostype(result);
  }

  //清空表单
  let reset = ()=>{
    // 清空市和区状态
    setCity([]);
    setDistrict([]);
  }




  //单独模拟 componentDidMount  获取医院列表的数据
  useEffect(() => {
    //  获取医院列表初始化数据
    getHospitalList();
    //获取省份信息
    getProvinceList()
    //获取医院类型
    getHospitalType();

  }, [])


  return (
    <Card>
      {/* 搜索表单部分 */}
      <Form
        layout='inline'
        form={form}
        onFinish={() => getHospitalList(1,5)}
        onReset={reset}
      >

        <Form.Item
          name="provinceCode"
        >
          <Select onChange={getCity} style={{ width: 180 }} placeholder="请选择省">
            {
              province.map(item => {
                return <Option key={item.id} value={item.id}>{item.name}</Option>
              })
            }


          </Select>
        </Form.Item>

        <Form.Item
          name="cityCode"
        >
          <Select onChange={getDistrict} style={{ width: 180 }} placeholder="请选择市">
            {
              city.map(item => {
                return <Option key={item.id} value={item.id}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>


        <Form.Item
          name="districtCode"
        >
          <Select style={{ width: 180 }} placeholder="请选择区">
            {
              district.map(item => {
                return <Option key={item.id} value={item.id}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>



        <Form.Item
          name="hosname"
        >
          <Input placeholder='医院名称' />
        </Form.Item>

        <Form.Item
          name="hoscode"

        >
          <Input placeholder='医院编号' />
        </Form.Item>


        <Form.Item
          name="hostype"
          className='mt'
        >
          <Select style={{ width: 180 }} placeholder="医院类型">
            {
              hostype.map(item => {
                return <Option key={item.id} value={item.value}>{item.name}</Option>
              })
            }
          </Select>
        </Form.Item>


        <Form.Item
          name="status"
          className='mt'
        >
          <Select style={{ width: 180 }} placeholder="医院状态">
            <Option value={1}>已上线</Option>
            <Option value={0}>未上线</Option>

          </Select>
        </Form.Item>


        <Form.Item className='mt'>
          <Button icon={<SearchOutlined />} type="primary" htmlType="submit">
            查询
          </Button>

          <Button type="default" className='ml' htmlType="reset">
            清空
          </Button>
        </Form.Item>
      </Form>

      {/* 表格部分 */}
      <Table
        rowKey="id"
        loading={loading}
        className='mt'
        columns={columns}
        dataSource={hospital}
        bordered
        scroll={{ x: 1200 }}
        pagination={{
          total,  //总数
          pageSize,  //每页展示数量
          current,  // 当前页码
          showQuickJumper: true,   //快速跳转值某页
          pageSizeOptions: [5, 10, 15, 20],
          showSizeChanger: true,
          showTotal(total: number) {
            return <span>总计：{total} 条</span>
          },
          onChange: getHospitalList
        }}

      />

    </Card>
  )
}
